<?php


namespace app\utils;


class QC
{
    public $app_id = '101998480';
    public $app_key = 'f04ce632260947be0f5a555fd9b98c57';
    public $callback = BASE_URL . '/qq/callback';
    function __construct(){

    }

    function GetAuthorizeUrl()
    {
        $url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" . $this->app_id . "&redirect_uri=" . urlencode($this->callback) . "&state=" . '';
        return $url;
    }

    function GetAccessToken($code)
    {
        $url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" . $this->app_id . "&client_secret=" . $this->app_key . "&code=" . $code . "&redirect_uri=".$this->callback;
        $s = file_get_contents($url);
        //$a = 'access_token=A53AFB257E8AE4F55D03C2A8D8BC4DDA&expires_in=7776000&refresh_token=F82DB7E433BF73BAC0FAF5FA0BE7D77B';
        if (substr_count($s, 'access_token') > 0) {
            //成功获取
            $arr = explode('&', $s);
            $result = [];
            foreach ($arr as $item){
                $kv = explode('=', $item);
                $key = $kv[0];
                $val = $kv[1];
                $result[$key]=$val;
            }
            return $result;
        }
        return null;
    }

    /**
     * @param $token
     * @return mixed|null
     */
    function GetOpenid($token)
    {
        if (empty($token)) {
            return null;
        }
        $url = "https://graph.qq.com/oauth2.0/me?access_token=".$token;
        $s = file_get_contents($url);
        $json = substr($s, 9, -3);
        return json_decode($json,true)['openid'];
    }

    function GetUser($token,$openid)
    {
        $url="https://graph.qq.com/user/get_user_info?access_token=".$token."&oauth_consumer_key=".$this->app_id."&openid=".$openid;//返回json格式
        $s = file_get_contents($url);
        return json_decode($s,true);
        //{ ret, msg, nickname, figureurl_qq_1, gender }
    }
}